<!--  -->
<template>
  <div class="categories-container">
    <!-- 搜索和操作区域 -->
    <div class="operation-section">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">
        新增分类
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="categoryList"
      border
      stripe
    >
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="categoryName" label="分类名称" />
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-pagination
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="categoryForm"
        :model="categoryForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="categoryForm.categoryName" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCategories, addCategory, updateCategory, deleteCategory } from '@/api/categories'

export default {
  name: 'Categories',
  data() {
    return {
      loading: false,
      categoryList: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      categoryForm: {
        categoryId: null,
        categoryName: ''
      },
      rules: {
        categoryName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      try {
        this.loading = true
        const res = await getCategories({ pageNum: this.pageNum })
        if (res.code === 200) {
          this.categoryList = res.data.list
          this.total = res.data.total
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
        this.$message.error('获取分类列表失败')
      } finally {
        this.loading = false
      }
    },
    handleAdd() {
      this.dialogTitle = '新增分类'
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑分类'
      this.categoryForm = { ...row }
      this.dialogVisible = true
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该分类吗？', '提示', {
          type: 'warning'
        })
        const res = await deleteCategory(row.categoryId)
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.getList()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除分类失败:', error)
          this.$message.error('删除失败')
        }
      }
    },
    submitForm() {
      this.$refs.categoryForm.validate(async valid => {
        if (valid) {
          try {
            const api = this.categoryForm.categoryId ? updateCategory : addCategory
            const res = await api(this.categoryForm)
            if (res.code === 200) {
              this.$message.success(`${this.dialogTitle}成功`)
              this.dialogVisible = false
              this.getList()
            }
          } catch (error) {
            console.error(`${this.dialogTitle}失败:`, error)
            this.$message.error(`${this.dialogTitle}失败`)
          }
        }
      })
    },
    resetForm() {
      this.$refs.categoryForm?.resetFields()
      this.categoryForm = {
        categoryId: null,
        categoryName: ''
      }
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.getList()
    }
  }
}
</script>

<style lang="less" scoped>
.categories-container {
  padding: 20px;

  .operation-section {
    margin-bottom: 16px;
  }

  .el-table {
    margin-bottom: 16px;
  }

  .pagination-section {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }
}
</style>
